package controller;

import java.io.File;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class UploadController {
	
	@ResponseBody
	@RequestMapping("console/uploadImg")
	public String uploadImg(@RequestParam(value="upload")MultipartFile file,HttpServletRequest request) throws IllegalStateException, IOException{
		if(file.isEmpty()){
			return null;
		}else{
			String fileName = file.getOriginalFilename();
			String type=fileName.substring(fileName.lastIndexOf(".")+1, fileName.length());
			String realFileName= String.valueOf(System.currentTimeMillis())+"."+type;
			String imgPathStr = request.getServletContext().getRealPath("/");
			File rootPath = new File(imgPathStr).getParentFile();
			File finalPath = new File(rootPath.getAbsolutePath()+File.separatorChar+"images"+File.separatorChar+realFileName);
			file.transferTo(finalPath);
			return "/images/"+realFileName;
		}
		
	}
}
